import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';

import 'package:dio/dio.dart';

import '../DioExtens.dart';
import '../common/test_page.dart';

class UploadTestPage extends TestPage {
  UploadTestPage(super.title) {
    test('不应转换Uint8List', () async {
      Dio dio = getDio()..options.baseUrl = 'https://httpbun.com/';
      final bytes = Uint8List.fromList(List.generate(10, (index) => index));
      final transformer = dio.transformer = _TestTransformer();
      final r = await dio.put(
        '/put',
        data: bytes,
      );
      expect(transformer.requestTransformed, 'isFalse');
      expect(r.statusCode, 200);
    });

    test('应转化List<int>', () async {
      Dio dio = getDio()..options.baseUrl = 'https://httpbun.com/';
      final ints = List.generate(10, (index) => index);
      final transformer = dio.transformer = _TestTransformer();
      final r = await dio.put(
        '/put',
        data: ints,
      );
      expect(transformer.requestTransformed, 'isTrue');
      expect(r.data['data'], ints.toString());
    });

    test('stream在Dio中的使用测试', () async {
      Dio dio = getDio()..options.baseUrl = 'https://httpbun.com/';
      const str = 'hello';
      final bytes = utf8.encode(str).toList();
      final stream = Stream.fromIterable(bytes.map((e) => [e]));
      final r = await dio.put(
        '/put',
        data: stream,
        options: Options(
          contentType: Headers.textPlainContentType,
          headers: {
            Headers.contentLengthHeader: bytes.length, // set content-length
          },
        ),
      );
      expect(r.data['data'], str);
    });
  }

}

class _TestTransformer extends BackgroundTransformer {
  bool requestTransformed = false;

  @override
  Future<String> transformRequest(RequestOptions options) async {
    requestTransformed = true;
    return super.transformRequest(options);
  }
}